package io.github.wanggit.antrpc.commons.utils;

/** 把10进制数转为62进制，以防止ID可能被字典猜测 */
public abstract class ID62 {

    private ID62() {
        throw new IllegalStateException();
    }

    private static final String BASE_62_CHAR =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int BASE = BASE_62_CHAR.length();

    /**
     * 转为10进制
     *
     * @param str 62进制字符串
     * @return 10进制
     */
    public static long toBase10(String str) {
        return toBase10(new StringBuilder(str).reverse().toString().toCharArray());
    }

    private static long toBase10(char[] chars) {
        long n = 0;
        int pow = 0;
        for (char item : chars) {
            n += toBase10(BASE_62_CHAR.indexOf(item), pow);
            pow++;
        }
        return n;
    }

    private static long toBase10(int n, int pow) {
        return n * (long) Math.pow(BASE, pow);
    }

    /**
     * 把10进制转为62进制字符串
     *
     * @param i 10进制
     * @return 62进制
     */
    public static String fromBase10(long i) {
        StringBuilder sb = new StringBuilder("");
        if (i == 0) {
            return "a";
        }
        while (i > 0) {
            i = fromBase10(i, sb);
        }
        return sb.reverse().toString();
    }

    private static long fromBase10(long i, StringBuilder sb) {
        int rem = (int) (i % BASE);
        sb.append(BASE_62_CHAR.charAt(rem));
        return i / BASE;
    }
}
